<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-my.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-my.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-my.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="vue,">





  <link rel="alternate" href="/atom.xml" title="徐子玉的笔记" type="application/atom+xml">






<meta name="description" content="本地安装vue-cli 前置条件 更新npm到最新版本   命令行运行:npm install -g npmnpm就自动为我们更新到最新版本     淘宝npm镜像使用方法 npm config set registry https://registry.npm.taobao.orgcnpm config set registry https://registry.npm.taobao.orgya">
<meta name="keywords" content="vue">
<meta property="og:type" content="article">
<meta property="og:title" content="vue3.0快速创建项目&amp;配置">
<meta property="og:url" content="http://blog.xuziyu.cn/vue3-0快速创建项目-配置.html">
<meta property="og:site_name" content="徐子玉的笔记">
<meta property="og:description" content="本地安装vue-cli 前置条件 更新npm到最新版本   命令行运行:npm install -g npmnpm就自动为我们更新到最新版本     淘宝npm镜像使用方法 npm config set registry https://registry.npm.taobao.orgcnpm config set registry https://registry.npm.taobao.orgya">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-03-16T07:34:33.689Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="vue3.0快速创建项目&amp;配置">
<meta name="twitter:description" content="本地安装vue-cli 前置条件 更新npm到最新版本   命令行运行:npm install -g npmnpm就自动为我们更新到最新版本     淘宝npm镜像使用方法 npm config set registry https://registry.npm.taobao.orgcnpm config set registry https://registry.npm.taobao.orgya">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"right","display":"always","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://blog.xuziyu.cn/vue3-0快速创建项目-配置.html">






  <title>vue3.0快速创建项目&配置 | 徐子玉的笔记</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b49e4132be4caecace2fcc27c6e8ec4d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>
<a href="https://github.com/knight-peter" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">徐子玉的笔记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Good Good Stady, Day Day Up.</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.xuziyu.cn/vue3-0快速创建项目-配置.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="徐子玉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="徐子玉的笔记">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">vue3.0快速创建项目&配置</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-25T12:51:00+08:00">
                2018-05-25
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/vue/" itemprop="url" rel="index">
                    <span itemprop="name">vue</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/vue3-0快速创建项目-配置.html#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="vue3-0快速创建项目-配置.html" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-eye" style="margin-right:7px;"></i>阅读次数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4,583 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  19 分钟
                </span>
              
            </div>
          

          

        </span></div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="本地安装vue-cli"><a href="#本地安装vue-cli" class="headerlink" title="本地安装vue-cli"></a>本地安装vue-cli</h2><hr>
<h3 id="前置条件"><a href="#前置条件" class="headerlink" title="前置条件"></a>前置条件</h3><ul>
<li>更新npm到最新版本  <blockquote>
<p>命令行运行:<br><code>npm install -g npm</code><br>npm就自动为我们更新到最新版本  </p>
</blockquote>
</li>
<li>淘宝npm镜像使用方法<blockquote>
<p><code>npm config set registry https://registry.npm.taobao.org</code><br><code>cnpm config set registry https://registry.npm.taobao.org</code><br><code>yarn config set registry https://registry.npm.taobao.org</code><br>配置后可通过下面方式来验证是否成功 ：<br>  <code>npm config get registry</code></p>
</blockquote>
</li>
<li>使用 npm 全局安装 vue-cli ：<br><code>npm i -g @vue/cli@3.0.0-beta.6</code>  </li>
</ul>
<a id="more"></a>
<h2 id="创建项目"><a href="#创建项目" class="headerlink" title="创建项目"></a>创建项目</h2><hr>
<ol>
<li>执行：<br><code>vue create my-project</code>  </li>
<li>此处有两个选择：  <ul>
<li><code>default (babel, eslint)</code>默认套餐，提供<code>babel</code>和<code>eslint</code>支持  </li>
<li><code>Manually select features</code>自己去选择需要的功能，提供更多的特性选择。比如如果想要支持 TypeScript ，就应该选择这一项。</li>
<li>可以使用<code>上下方向键</code>来切换选项。如果只需要 <code>babel</code> 和 <code>eslint</code> 支持，那么选择第一项，就完事了，静静等待 vue 初始化项目。</li>
<li>vue-cli 内置支持了8个功能特性，可以多选：使用方向键在特性选项之间切换，使用空格键选中当前特性，使用 a 键切换选择所有，使用 i 键翻转选项。</li>
<li>对于每一项的功能，此处做个简单描述：<ul>
<li><code>TypeScript</code> 支持使用 <code>TypeScript</code> 书写源码</li>
<li><code>Progressive Web App (PWA) Support</code> PWA 支持。</li>
<li><code>Router</code> 支持 vue-router 。</li>
<li><code>Vuex</code> 支持 vuex 。</li>
<li><code>CSS Pre-processors</code> 支持 CSS 预处理器。</li>
<li><code>Linter / Formatter</code> 支持代码风格检查和格式化。</li>
<li><code>Unit Testing</code> 支持单元测试。</li>
<li><code>E2E Testing</code> 支持 E2E 测试。  </li>
</ul>
</li>
<li>我选择了 <code>Router</code>，<code>Vuex</code>，<code>CSS Pre-processors</code>，<code>Linter / Formatter</code>  </li>
</ul>
</li>
<li>按住enter进入下一步，接下来都是对之前每项选项的更详细的选择。  <ul>
<li><strong>css</strong>选择<code>SCSS/SASS</code></li>
<li><strong>Linter / Formatter</strong>选择<code>prettier</code>  </li>
<li>这一步就是要选择配置文件的位置了。对于 <code>Babel</code> 、 <code>PostCSS</code> 等，都可以有自己的配置文件： <code>.babelrc</code> 、 <code>.postcssrc</code> 等等，同时也可以把配置信息放在 <code>package.json</code> 里面。此处出于对编辑器（ Visual Studio Code ）的友好支持（编辑器一般默认会在项目根目录下寻找配置文件），选择把配置文件放在外面，选择 <code>In dedicated config files</code></li>
<li>待补充  </li>
</ul>
</li>
<li><code>Save this as a preset for future projects?</code>这个就是问要不要把当前的这一系列选项配置保存起来，方便下一次创建项目时复用。选择<code>y</code>。</li>
<li>选完之后， vue-cli 就根据前面选择的内容，开始初始化项目了。</li>
</ol>
<h2 id="启动项目"><a href="#启动项目" class="headerlink" title="启动项目"></a>启动项目</h2><hr>
<p>初始完之后，进入到项目根目录：<br><code>cd my-project</code><br>启动项目：<br><code>npm run serve</code><br>稍等一会儿，可以看到自动在浏览器中打开了  </p>
<h4 id="安装PostCSS插件"><a href="#安装PostCSS插件" class="headerlink" title="安装PostCSS插件"></a>安装PostCSS插件</h4><ul>
<li>通过<code>Vue-cli</code>构建的项目，在项目的根目录下有一个<code>.postcssrc.js</code>，默认情况下已经有了：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">module.exports = &#123;</span><br><span class="line">        plugins: &#123;</span><br><span class="line">          autoprefixer: &#123;&#125;</span><br><span class="line">        &#125;</span><br><span class="line">&#125;</span><br><span class="line">```    </span><br><span class="line">配置成</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>module.exports = {<br>        plugins: {<br>          “postcss-import”:{},<br>          “postcss-url”:{},<br>          “autoprefixer”: {}<br>        }<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"> - 安装`postcss-import`和`postcss-url`插件  </span><br><span class="line">	*	`$ npm install postcss-import`和`$ npm install postcss-url`</span><br><span class="line">	*	`postcss-import`相关配置[*点击这里*](http://github.com/postcss/postcss-import &quot;postcss-import的github仓库&quot;)。主要功有是解决`@import`引入路径问题。使用这个插件，可以让你很轻易的使用本地文件、`node_modules`或者`web_modules`的文件。这个插件配合`postcss-url`让你引入文件变得更轻松。  </span><br><span class="line">    *	`postcss-url`相关配置可以[*点击这里*](https://github.com/postcss/postcss-url &quot;postcss-url的github仓库&quot;)。该插件主要用来处理文件，比如图片文件、字体文件等引用路径的处理。在Vue项目中，`vue-loader`已具有类似的功能，只需要配置中将`vue-loader`配置进去。  </span><br><span class="line">    *	`autoprefixer`插件是用来自动处理浏览器前缀的一个插件。如果你配置了`postcss-cssnext`，其中就已具备了`autoprefixer`的功能。在配置的时候，未显示的配置相关参数的话，表示使用的是[`Browserslist`](https://github.com/ai/browserslist &quot;Browserslist的github仓库地址&quot;)指定的列表参数，你也可以像这样来指定`last 2 versions` 或者 `&gt; 5%`。如此一来，你在编码时不再需要考虑任何浏览器前缀的问题，可以专心撸码。这也是PostCSS最常用的一个插件之一。  </span><br><span class="line">    </span><br><span class="line">###	其他插件  </span><br><span class="line">我们要完成vw的布局兼容方案，或者说让我们能更专心的撸码，还需要配置下面的几个PostCSS插件：</span><br><span class="line"></span><br><span class="line">*	[postcss-aspect-ratio-mini](http://github.com/yisibl/postcss-aspect-ratio-mini)</span><br><span class="line">*	[postcss-px-to-viewport](http://github.com/evrone/postcss-px-to-viewport)</span><br><span class="line">*	[postcss-write-svg](http://github.com/jonathantneal/postcss-write-svg)</span><br><span class="line">*	[postcss-cssnext](http://github.com/MoOx/postcss-cssnext)</span><br><span class="line">*	[cssnano](http://github.com/ben-eb/cssnano)</span><br><span class="line">*	[postcss-viewport-units](http://github.com/springuper/postcss-viewport-units)  </span><br><span class="line"></span><br><span class="line">要使用  </span><br><span class="line">安装成功后，在项目根目录下的`package.json`文件中，可以看到新安装的依赖包：</span><br></pre></td></tr></table></figure></p>
<p>“dependencies”: {<br>    “cssnano”: “^3.10.0”,<br>    “postcss-aspect-ratio-mini”: “^0.0.2”,<br>    “postcss-cssnext”: “^3.1.0”,<br>    “postcss-import”: “^11.1.0”,<br>    “postcss-px-to-viewport”: “^0.0.3”,<br>    “postcss-url”: “^7.3.2”,<br>    “postcss-viewport-units”: “^0.1.4”,<br>    “postcss-write-svg”: “^3.0.1”,<br>    “vue”: “^2.5.16”,<br>    “vue-router”: “^3.0.1”,<br>    “vuex”: “^3.0.1”<br>  },<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">接下来在`.postcssrc.js`文件对新安装的`PostCSS`插件进行配置：</span><br></pre></td></tr></table></figure></p>
<p>module.exports = {<br>  plugins: {<br>    “postcss-import”: {},<br>    “postcss-url”: {},<br>    //“autoprefixer”: {},<br>    “postcss-aspect-ratio-mini”: {},<br>    “postcss-write-svg”: {<br>      utf8: false<br>    },<br>    “postcss-cssnext”: {},<br>    “postcss-px-to-viewport”: {<br>      viewportWidth: 750, //视窗的宽度，对应的是我们设计稿的宽度，一般是750<br>      viewportHeight: 1334, //视窗的高度，根据750设备的宽度来置顶，一般指定1334，也可以不配置<br>      unitPrecision: 3, //指定’px’转换为视窗单位值的小数位数（很多时候无法整除）<br>      viewportUnit: ‘vw’, //指定需要转换成的视窗单位，建议使用vw<br>      selectorBlackList: [‘.ignore’, ‘.hairlines’, ‘.g-vw-no’], //指定不转行为视窗单位的类，可以自定义，可以无限添加，建议定义一至两个通用的类名<br>      minPixeValue: 1, //小于或等于’1px’不转换为视窗单位，你也可以设置为你想要的值<br>      mediaQuery: false //允许在媒体查询中转换’px’<br>    },<br>    “postcss-viewport-units”: {},<br>    “cssnano”: {<br>      preset: “advanced”,<br>      autoprefixer: false,<br>      “postcss-zindex”: false<br>    }<br>  }<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">&gt; 特别声明：由于`cssnext`和`cssnano`都具有`autoprefixer`,事实上只需要一个，所以把默认的`autoprefixer`删除掉，然后把`cssnano`中的`autoprefixer`设置为`false`。对于其他的插件使用，稍后会简单的介绍。</span><br><span class="line"></span><br><span class="line">由于配置文件修改了，所以重新跑一下`npm run dev`。项目就可以正常看到了。接下来简单的介绍一下后面安装的几个插件的作用。</span><br><span class="line">##### postcss-cssnext</span><br><span class="line"></span><br><span class="line">`postcss-cssnext`其实就是`cssnext`。该插件可以让我们使用CSS未来的特性，其会对这些特性做相关的兼容性处理。其包含的特性主要有：  </span><br><span class="line">有关于cssnext的每个特性的操作文档，可以[点击这里](http://cssnano.co/guides/getting-started/)浏览。</span><br><span class="line">##### cssnano</span><br><span class="line"></span><br><span class="line">`cssnano`主要用来压缩和清理`CSS`代码。在`Webpack`中，`cssnano`和`css-loader`捆绑在一起，所以不需要自己加载它。不过你也可以使用`postcss-loader`显式的使用`cssnano`。有关于`cssnano`的详细文档，可以点击这里获取。</span><br><span class="line"></span><br><span class="line">在`cssnano`的配置中，使用了`preset: &quot;advanced&quot;`，所以我们需要另外安装：</span><br></pre></td></tr></table></figure></p>
<p>npm i cssnano-preset-advanced –save-dev<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`cssnano`集成了一些其他的`PostCSS`插件，如果你想禁用`cssnano`中的某个插件的时候，可以像下面这样操作：</span><br></pre></td></tr></table></figure></p>
<p>“cssnano”: {<br>    autoprefixer: false,<br>    “postcss-zindex”: false<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">上面的代码把`autoprefixer`和`postcss-zindex`禁掉了。前者是有重复调用，后者是一个讨厌的东东。只要启用了这个插件，`z-index`的值就会重置为1。这是一个天坑，***千万记得将`postcss-zindex`设置为`false`***。</span><br><span class="line">postcss-px-to-viewport</span><br><span class="line"></span><br><span class="line">postcss-px-to-viewport插件主要用来把px单位转换为vw、vh、vmin或者vmax这样的视窗单位，也是vw适配方案的核心插件之一。</span><br><span class="line"></span><br><span class="line">在配置中需要配置相关的几个关键参数：</span><br></pre></td></tr></table></figure></p>
<p>“postcss-px-to-viewport”: {<br>    viewportWidth: 750,      // 视窗的宽度，对应的是我们设计稿的宽度，一般是750<br>    viewportHeight: 1334,    // 视窗的高度，根据750设备的宽度来指定，一般指定1334，也可以不配置<br>    unitPrecision: 3,        // 指定<code>px</code>转换为视窗单位值的小数位数（很多时候无法整除）<br>    viewportUnit: ‘vw’,      // 指定需要转换成的视窗单位，建议使用vw<br>    selectorBlackList: [‘.ignore’, ‘.hairlines’],  // 指定不转换为视窗单位的类，可以自定义，可以无限添加,建议定义一至两个通用的类名<br>    minPixelValue: 1,       // 小于或等于<code>1px</code>不转换为视窗单位，你也可以设置为你想要的值<br>    mediaQuery: false       // 允许在媒体查询中转换<code>px</code><br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">目前出视觉设计稿，我们都是使用750px宽度的，那么100vw = 750px，即1vw = 7.5px。那么我们可以根据设计图上的px值直接转换成对应的vw值。在实际撸码过程，不需要进行任何的计算，直接在代码中写px，比如：</span><br></pre></td></tr></table></figure></p>
<p>.test {<br>    border: .5px solid black;<br>    border-bottom-width: 4px;<br>    font-size: 14px;<br>    line-height: 20px;<br>    position: relative;<br>}<br>[w-188-246] {<br>    width: 188px;<br>}</p>
<p>编译出来的CSS：</p>
<p>.test {<br>    border: .5px solid #000;<br>    border-bottom-width: .533vw;<br>    font-size: 1.867vw;<br>    line-height: 2.667vw;<br>    position: relative;<br>}<br>[w-188-246] {<br>    width: 25.067vw;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">在不想要把`px`转换为`vw`的时候，首先在对应的元素（`html`）中添加配置中指定的类名`.ignore`或`.hairlines`(`.hairlines`一般用于设置`border-width:0.5px`的元素中)：</span><br></pre></td></tr></table></figure></p>
<p><div class="box ignore"></div><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">写CSS的时候：</span><br></pre></td></tr></table></figure></p>
<p>.ignore {<br>    margin: 10px;<br>    background-color: red;<br>}<br>.box {<br>    width: 180px;<br>    height: 300px;<br>}<br>.hairlines {<br>    border-bottom: 0.5px solid red;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编译出来的CSS:</span><br></pre></td></tr></table></figure></p>
<p>.box {<br>    width: 24vw;<br>    height: 40vw;<br>}<br>.ignore {<br>    margin: 10px; /<em>.box元素中带有.ignore类名，在这个类名写的<code>px</code>不会被转换</em>/<br>    background-color: red;<br>}<br>.hairlines {<br>    border-bottom: 0.5px solid red;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">上面解决了`px`到`vw`的转换计算。那么在哪些地方可以使用`vw`来适配我们的页面。根据相关的测试：</span><br><span class="line"></span><br><span class="line">* 容器适配，可以使用vw</span><br><span class="line">* 文本的适配，可以使用vw</span><br><span class="line">* 大于1px的边框、圆角、阴影都可以使用vw</span><br><span class="line">* 内距和外距，可以使用vw</span><br><span class="line"></span><br><span class="line">##### postcss-aspect-ratio-mini</span><br><span class="line"></span><br><span class="line">[`postcss-aspect-ratio-mini`](http://github.com/yisibl/postcss-aspect-ratio-mini)主要用来处理元素容器宽高比。在实际使用的时候，具有一个默认的结构</span><br></pre></td></tr></table></figure></p>
<p><div aspectratio><br>    <div aspectratio-content></div><br></div><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">在实际使用的时候，你可以把自定义属性`aspectratio`和`aspectratio-content`换成相应的类名，比如：</span><br></pre></td></tr></table></figure></p>
<p><div class="aspectratio"><br>    <div class="aspectratio-content"></div><br></div><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">我个人比较喜欢用__自定义属性__，它和类名所起的作用是同等的。结构定义之后，需要在你的样式文件中添加一个**统一的宽度比默认属性**：</span><br></pre></td></tr></table></figure></p>
<p>[aspectratio] {<br>    position: relative;<br>}<br>[aspectratio]::before {<br>    content: ‘’;<br>    display: block;<br>    width: 1px;<br>    margin-left: -1px;<br>    height: 0;<br>}<br>/<em>aspectratio-content存放内容，自由填满，利用伪元素::before和::after来撑开容器</em>/<br>[aspectratio-content] {<br>    position: absolute;<br>    top: 0;<br>    left: 0;<br>    right: 0;<br>    bottom: 0;<br>    width: 100%;<br>    height: 100%;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">如果我们想要做一个`188:246`（`188`是容器宽度，`246`是容器高度）这样的比例容器，只需要这样使用：</span><br></pre></td></tr></table></figure></p>
<p>[w-188-246] {<br>    aspect-ratio: ‘188:246’;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">有一点需要特别注意：`aspect-ratio`属性不能和其他属性写在一起，否则编译出来的属性只会留下`aspect-ratio`的值，比如：</span><br></pre></td></tr></table></figure></p>
<p><div aspectratio w-188-246 class="color"></div><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编译前的CSS如下：</span><br></pre></td></tr></table></figure></p>
<p>[w-188-246] {<br>    width: 188px;<br>    background-color: red;<br>    aspect-ratio: ‘188:246’;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编译之后：</span><br></pre></td></tr></table></figure></p>
<p>[w-188-246]:before {<br>    padding-top: 130.85106382978725%;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">主要是因为在插件中做了相应的处理，不在每次调用`aspect-ratio`时，生成前面指定的默认样式代码，这样代码没那么冗余。所以在使用的时候，需要把`width`和`background-color`分开来写：</span><br></pre></td></tr></table></figure></p>
<p>[w-188-246] {<br>    width: 188px;<br>    background-color: red;<br>}<br>[w-188-246] {<br>    aspect-ratio: ‘188:246’;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">这个时候，编译出来的CSS就正常了：</span><br></pre></td></tr></table></figure></p>
<p>[w-188-246] {<br>    width: 25.067vw;/<em>撑开宽度</em>/<br>    background-color: red;<br>}<br>[w-188-246]:before {<br>    padding-top: 130.85106382978725%;/<em>撑开高度</em>/<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">有关于宽高比相关的详细介绍，如果大家感兴趣的话，可以阅读下面相关的文章：</span><br><span class="line"></span><br><span class="line">* [CSS实现长宽比的几种方案](http://www.w3cplus.com/css/aspect-ratio.html)</span><br><span class="line">* [容器长宽比](http://www.w3cplus.com/css/aspect-ratio-boxes.html)</span><br><span class="line">* [Web中如何实现纵横比](http://www.w3cplus.com/css/experiments-in-fixed-aspect-ratios.html)</span><br><span class="line">* [实现精准的流体排版原理](http://www.w3cplus.com/css/css-polyfluidsizing-using-calc-vw-breakpoints-and-linear-equations.html)</span><br><span class="line"></span><br><span class="line">&gt; 目前采用`PostCSS`插件只是一个过渡阶段，在将来我们可以直接在CSS中使用`aspect-ratio`属性来实现长宽比。</span><br><span class="line">##### postcss-write-svg</span><br><span class="line"></span><br><span class="line">[`postcss-write-svg`](http://github.com/jonathantneal/postcss-write-svg)插件主要用来处理移动端`1px`的解决方案。该插件主要使用的是`border-image`和`background`来做`1px`的相关处理。比如：</span><br></pre></td></tr></table></figure></p>
<p>@svg 1px-border {<br>    height: 2px;<br>    @rect {<br>        fill: var(–color, black);<br>        width: 100%;<br>        height: 50%;<br>    }<br>}<br>.example {<br>    border: 1px solid transparent;<br>    border-image: svg(1px-border param(–color #00b1ff)) 2 2 stretch;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编译出来的CSS:</span><br></pre></td></tr></table></figure></p>
<p>.example {<br>    border: 1px solid transparent;<br>    border-image: url(“data:image/svg+xml;charset=utf-8,%3Csvg xmlns=’<a href="http://www.w3.org/2000/svg&#39;" target="_blank" rel="noopener">http://www.w3.org/2000/svg&#39;</a> height=’2px’%3E%3Crect fill=’%2300b1ff’ width=’100%25’ height=’50%25’/%3E%3C/svg%3E”) 2 2 stretch;<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">上面演示的是使用`border-image`方式，除此之外还可以使用`background-image`来实现。比如：</span><br></pre></td></tr></table></figure></p>
<p>@svg square {<br>    @rect {<br>        fill: var(–color, black);<br>        width: 100%;<br>        height: 100%;<br>    }<br>}</p>
<p>#example {<br>    background: white svg(square param(–color #00b1ff));<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">编译出来就是：</span><br></pre></td></tr></table></figure></p>
<p>#example {<br>    background: white url(“data:image/svg+xml;charset=utf-8,%3Csvg xmlns=’<a href="http://www.w3.org/2000/svg&#39;%3E%3Crect" target="_blank" rel="noopener">http://www.w3.org/2000/svg&#39;%3E%3Crect</a> fill=’%2300b1ff’ width=’100%25’ height=’100%25’/%3E%3C/svg%3E”);<br>}<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">解决`1px`的方案除了这个插件之外，还有其他的方法。可以阅读前期整理的《[再谈Retina下`1px`的解决方案](http://www.w3cplus.com/css/fix-1px-for-retina.html)》一文。</span><br><span class="line"></span><br><span class="line">&gt; **特别声明**：由于有一些低端机对`border-image`支持度不够友好，个人建议你使用`background-image`的这个方案。</span><br><span class="line">##### CSS Modules</span><br><span class="line"></span><br><span class="line">Vue中的`vue-loader`已经集成了[CSS Modules](http://github.com/css-modules/css-modules)的功能，个人建议在项目中开始使用CSS Modules。特别是在Vue和React的项目中，CSS Modules具有很强的优势和灵活性。建议看看CSS In JS相关的资料。在Vue中，使用CSS Modules的相关文档可以阅读Vue官方提供的文档[《CSS Modules》](http://vue-loader.vuejs.org/en/features/css-modules.html)。</span><br><span class="line">##### postcss-viewport-units</span><br><span class="line"></span><br><span class="line">[`postcss-viewport-units`](http://github.com/springuper/postcss-viewport-units)插件主要是给CSS的属性添加`content`的属性，配合[`viewport-units-buggyfill`](http://github.com/rodneyrehm/viewport-units-buggyfill)库给`vw`、`vh`、`vmin`和`vmax`做适配的操作。</span><br><span class="line"></span><br><span class="line">这是实现`vw`布局必不可少的一个插件，因为少了这个插件，这将是一件痛苦的事情。后面你就清楚。</span><br><span class="line"></span><br><span class="line">到此为止，有关于所需要的PostCSS已配置完。并且简单的介绍了各个插件的作用，至于详细的文档和使用，可以参阅对应插件的官方文档。</span><br><span class="line">### vw兼容方案</span><br><span class="line">使用`viewport`的`polyfill`：`Viewport Units Buggyfill`。使用`viewport-units-buggyfill`主要分以下几步走：</span><br><span class="line">##### 引入JavaScript文件</span><br><span class="line"></span><br><span class="line">`viewport-units-buggyfill`主要有两个JavaScript文件：`viewport-units-buggyfill.js`和`viewport-units-buggyfill.hacks.js`。你只需要在你的HTML文件中引入这两个文件。比如在Vue项目中的`index.html`引入它们：</span><br></pre></td></tr></table></figure></p>
<p><script src="//g.alicdn.com/fdilab/lib3rd/viewport-units-buggyfill/0.6.2/??viewport-units-buggyfill.hacks.min.js,viewport-units-buggyfill.min.js"></script><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">你也可以使用其他的在线CDN地址，也可将这两个文件合并压缩成一个`.js`文件。这主要看你自己的兴趣了。</span><br><span class="line"></span><br><span class="line">第二步，在HTML文件中调用`viewport-units-buggyfill`，比如：</span><br></pre></td></tr></table></figure></p>
<p><script><br>    window.onload = function () {<br>        window.viewportUnitsBuggyfill.init({<br>            hacks: window.viewportUnitsBuggyfillHacks<br>        });<br>    }<br></script><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">为了你Demo的时候能获取对应机型相关的参数，我在示例中添加了一段额外的代码，估计会让你有点烦：</span><br><span class="line">```javascript</span><br><span class="line">&lt;script&gt;</span><br><span class="line">window.onload = function () &#123;</span><br><span class="line">     window.viewportUnitsBuggyfill.init(&#123;</span><br><span class="line">     hacks: window.viewportUnitsBuggyfillHacks</span><br><span class="line">     &#125;);</span><br><span class="line"></span><br><span class="line">     var winDPI = window.devicePixelRatio;</span><br><span class="line">     var uAgent = window.navigator.userAgent;</span><br><span class="line">     var screenHeight = window.screen.height;</span><br><span class="line">     var screenWidth = window.screen.width;</span><br><span class="line">     var winWidth = window.innerWidth;</span><br><span class="line">     var winHeight = window.innerHeight;</span><br><span class="line"></span><br><span class="line">     alert(</span><br><span class="line">         &quot;Windows DPI:&quot; + winDPI +</span><br><span class="line">         &quot;;\ruAgent:&quot; + uAgent +</span><br><span class="line">         &quot;;\rScreen Width:&quot; + screenWidth +</span><br><span class="line">         &quot;;\rScreen Height:&quot; + screenHeight +</span><br><span class="line">         &quot;;\rWindow Width:&quot; + winWidth +</span><br><span class="line">         &quot;;\rWindow Height:&quot; + winHeight</span><br><span class="line">     )</span><br><span class="line"> &#125;</span><br><span class="line">&lt;/script&gt;</span><br></pre></td></tr></table></figure></p>
<p>具体的使用。在你的CSS中，只要使用到了<code>viewport</code>的单位（<code>vw</code>、<code>vh</code>、<code>vmin</code>或<code>vmax</code> ）地方，需要在样式中添加<code>content</code>：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">.my-viewport-units-using-thingie &#123;</span><br><span class="line">    width: 50vmin;</span><br><span class="line">    height: 50vmax;</span><br><span class="line">    top: calc(50vh - 100px);</span><br><span class="line">    left: calc(50vw - 100px);</span><br><span class="line"></span><br><span class="line">    /* hack to engage viewport-units-buggyfill */</span><br><span class="line">    content: &apos;viewport-units-buggyfill; width: 50vmin; height: 50vmax; top: calc(50vh - 100px); left: calc(50vw - 100px);&apos;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这可能会令你感到恶心，而且我们不可能每次写vw都去人肉的计算。特别是在我们的这个场景中，咱们使用了<code>postcss-px-to-viewport</code>这个插件来转换<code>vw</code>，更无法让我们人肉的去添加<code>content</code>内容。</p>
<p>这个时候就需要前面提到的<code>postcss-viewport-units</code>插件。这个插件将让你无需关注<code>content</code>的内容，插件会自动帮你处理。  </p>
<p><a href="http://github.com/rodneyrehm/viewport-units-buggyfill" target="_blank" rel="noopener"><strong>Viewport Units Buggyfill</strong></a>还提供了其他的功能。详细的这里不阐述了。但是<code>content</code>也会引起一定的副作用。比如<code>img</code>和伪元素<code>::before</code>(<code>:before</code>)或<code>::after</code>（<code>:after</code>）。在<code>img</code>中<code>content</code>会引起部分浏览器下，图片不会显示。这个时候需要全局添加：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">img &#123;</span><br><span class="line">    content: normal !important;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>而对于<code>::after</code>之类的，就算是里面使用了<code>vw</code>单位，Viewport Units Buggyfill对其并不会起作用。比如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">// 编译前</span><br><span class="line">.after &#123;</span><br><span class="line">    content: &apos;after content&apos;;</span><br><span class="line">    display: block;</span><br><span class="line">    width: 100px;</span><br><span class="line">    height: 20px;</span><br><span class="line">    background: green;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 编译后</span><br><span class="line">.after[data-v-469af010] &#123;</span><br><span class="line">    content: &quot;after content&quot;;</span><br><span class="line">    display: block;</span><br><span class="line">    width: 13.333vw;</span><br><span class="line">    height: 2.667vw;</span><br><span class="line">    background: green;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个时候我们需要通过添加<strong>额外的标签</strong>来替代伪元素（这个情景我没有测试到，后面自己亲测一下）。</p>
<p>到了这个时候，你就不需要再担心兼容问题了。<br>整个示例的源码，可以点击<a href="http://www.w3cplus.com/sites/default/files/blogs/2018/1801/vw-layout.zip" title="示例源码" target="_blank" rel="noopener">这里下载</a>。</p>
<blockquote>
<p>如果你下载了示例源码，先要确认你的系统环境能跑Vue的项目，然后下载下来之后，解压缩，接着运行<code>npm i</code>，再运行<code>npm run dev</code>，你就可以看到效果了。</p>
</blockquote>
<h2 id="打包上线"><a href="#打包上线" class="headerlink" title="打包上线"></a>打包上线</h2><hr>
<p>在开发完项目之后，就应该打包上线了。 vue-cli 也提供了打包的命令，在项目根目录下执行：<br><code>npm run build</code><br>执行完之后，可以看到在项目根目录下多出了一个 dist 目录，该目录下就是打包好的所有静态资源，直接部署到静态资源服务器就好了。<br>实际上，在部署的时候要注意，假设静态服务器的域名是 <code>http://static.baidu.com</code> ，那么对应到访问 <code>&lt;项目根目录&gt;/dist/index.html</code> 的 URL 一定要是 <code>http://static.baidu.com/index.html</code> ，其他的静态资源以此类推。</p>

      
    </div>
    
    
    

    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="徐子玉 wechat" style="width: 200px; max-width: 100%;">
    <div>欢迎您扫一扫上面的微信二维码，订阅我的公众号！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat-reward.gif" alt="徐子玉 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay-reward.gif" alt="徐子玉 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/vue/" <i class="fa fa-tag"> vue</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/vue解决跨域问题.html" rel="next" title="vue解决跨域问题">
                <i class="fa fa-chevron-left"></i> vue解决跨域问题
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/创建py文件时自定义头部模板.html" rel="prev" title="创建py文件时自定义头部模板">
                创建py文件时自定义头部模板 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="徐子玉">
            
              <p class="site-author-name" itemprop="name">徐子玉</p>
              <p class="site-description motion-element" itemprop="description">喜欢跑步的吃货才是一个好程序猿</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/knight-peter" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:xuqipeter@qq.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.imooc.com" title="慕课网" target="_blank" rel="external nofollow">慕课网</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com/" title="廖雪峰的官方网站" target="_blank" rel="external nofollow">廖雪峰的官方网站</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#本地安装vue-cli"><span class="nav-number">1.</span> <span class="nav-text">本地安装vue-cli</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#前置条件"><span class="nav-number">1.1.</span> <span class="nav-text">前置条件</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建项目"><span class="nav-number">2.</span> <span class="nav-text">创建项目</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#启动项目"><span class="nav-number">3.</span> <span class="nav-text">启动项目</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#安装PostCSS插件"><span class="nav-number">3.0.1.</span> <span class="nav-text">安装PostCSS插件</span></a></li></ol></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#打包上线"><span class="nav-number">4.</span> <span class="nav-text">打包上线</span></a></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">徐子玉</span>

  
</div>

<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">NexT.Mist</a> v5.1.4</div>

-->

<p>Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a></p>
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytsHS66l';
      var conf = 'e2a8af2f881183b9aa2cdfcaa43bf747';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  









  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
